<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Yjb_model extends CI_Model {
	function __construct(){
        parent::__construct();
    }
    
    function add($data = array()){
    	$this->db->insert('zjy_yjb_borrow', $data);
		$borrow_id = $this->db->insert_id();
		return $borrow_id;
    }
    
    function get_list($data = array()){
    	$_where = " where id>0";
    	if (isset($data['where']['fstatus']) && $data['where']['fstatus']>0){
    		$_where .= " and fstatus={$data['where']['fstatus']}";
    	}
    	if (isset($data['where']['user_id']) && $data['where']['user_id']>0){
    		$_where .= " and user_id={$data['where']['user_id']}";
    	}
    	if (isset($data['where']['title']) && $data['where']['title']!=''){
    		$_where .= " and title='{$data['where']['title']}'";
    	}
    	
   	 if(isset($data['where']['auto_verify_time']) && $data['where']['auto_verify_time'] >0){
			$_where .= " and auto_verify_time = ".$data['where']['auto_verify_time'];
		}
		
		if(isset($data['where']['is_check']) && $data['where']['is_check'] >0){
			$_where .= " and is_check = ".$data['where']['is_check'];
		}
		
    	if (isset($data['order']) && $data['order']='jindu'){
    		$_order = " order by (account_yes/account) asc,id desc";
    	}else{
    		$_order = " order by fstatus asc,id desc";
    	}
    	$_limit = "";
    	if (isset($data['per_page']) && isset($data['page_size'])){
    		$_limit = " limit {$data['per_page']},{$data['page_size']}";
    	}
    	
    	$sql = "select count(id) as count from zjy_yjb_borrow".$_where.$_order;
    	$query = $this->db->query($sql);
		$count = $query->row()->count;
		$sql = "select * from zjy_yjb_borrow".$_where.$_order.$_limit;
		
		$query = $this->db->query($sql);
		$list = $query->result_array();
		return array(
			'count' => $count,
			'list' => $list
		);
    }
    
    function get_by_id($id=0){
    	$id = intval($id);
    	$sql = "select p1.*,p2.username from zjy_yjb_borrow as p1 left join zjy_user as p2 
    		on p1.user_id=p2.user_id where p1.id={$id}";
    	
		$query = $this->db->query($sql);
		$row = $query->row_array();
		return $row;
    }
    
    function get_tender_by_id($id=0){
    	$id = intval($id);
    	$sql = "select p1.*,p2.username,p2.realname,p2.card_id,p2.phone from zjy_yjb_tender as p1 left join zjy_user as p2 
    		on p1.user_id=p2.user_id where p1.id={$id}";
    	
		$query = $this->db->query($sql);
		$row = $query->row_array();
		return $row;
    }
    
    function update($data,$where){
    	$this->db->where($where);
		$query = $this->db->update('zjy_yjb_borrow', $data);
		$res = $this->db->affected_rows();
		return $res;
    }
    
    function invest($data){
    	$yjbId = $data['yjb_id'];
		$user_id = $data['user_id'];
		$account = $data['account'];
		$yjb = self::get_by_id($yjbId);
		$borrow_url = "<a href='/borrow/slobj/{$yjb['id']}.html' target=_blank>{$yjb['title']}</a>";
		$tender_id = self::add_tender($data);
		if ($tender_id > 0){
			$this->load->model('Account_model');
			$this->load->model('User_model');
			$this->load->model('Message_model');
			$this->load->model('Credit_model');
			
			$this->db->trans_start();
			$this->db->query("update zjy_yjb_borrow set account_yes=account_yes+{$account},tender_times=tender_times+1 where id={$yjbId}");
			
			$eq['account'] 			= $data['account'];
			$eq['apr'] 				= $data['apr'];
			$eq['time_limit'] 		= 1;
			$eq['style'] 			= 0;
	        $eq['is_day']			= 1;
	        $eq['time_limit_day']	= $data['time_limit_day'];
	       // echo 111;
			$result 				= equal_interest($eq);
			//var_dump($result);
			$_repay_time = time()+$data['time_limit_day']*60*60*24;//应还时间
			$repayment_account 		= 0;//应还金额
			foreach ($result as $key => $value){
				$repayment_account += $value['repayment_account'];
			}
			$repayment_account = round($repayment_account,2);
			$_interest = round($repayment_account-$account,2);//利息
			$this->db->query(" update zjy_yjb_tender set repayment_account='{$repayment_account}',
				repay_time ='{$_repay_time}',interest = '{$_interest}' where id={$tender_id}");
			
			//echo 111;
			//投标金额冻结
			$account_result 	 = $this->Account_model->get_account($user_id);
			$log1['user_id'] 	= $user_id;
			$log1['ftype'] 		= TENDER;
			$log1['money'] 		= $account;
			$log1['total'] 		= $account_result['total'];
			$log1['use_money'] 	= $account_result['use_money']-$log1['money'];
			$log1['no_use_money']= $account_result['no_use_money']+$log1['money'];
			$log1['collection'] = $account_result['collection'];
			$log1['to_user'] 	= $yjb['user_id'];
			$log1['remark'] 	= "投标冻结资金";
			$log1['add_time'] 	= $data['add_time'];
			$log1['addip'] 		= $data['addip'];
			//$this->db->insert('zjy_account_log_'.$mode, $log1);
			$this->db->query("update zjy_account set use_money=use_money-{$log1['money']},no_use_money=no_use_money+{$log1['money']} where user_id={$user_id}");
			
			//扣除投资者的金钱。
			unset($account_result);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log2['user_id'] 	= $user_id;
			$log2['ftype'] 		= INVEST;
			$log2['money'] 		= $account;
			$log2['total'] 		= $account_result['total']-$log2['money'];
			$log2['use_money'] 	= $account_result['use_money'];
			$log2['no_use_money']= $account_result['no_use_money']-$log2['money'];
			$log2['collection'] = $account_result['collection'];
			$log2['to_user'] 	= $yjb['user_id'];
			$log2['remark'] 	= "投标成功费用扣除";
			$log2['add_time'] 	= $data['add_time'];
			$log2['addip'] 		= $data['addip'];
			//$this->db->insert('zjy_account_log_'.$mode, $log2);
			$this->db->query("update zjy_account set total=total-{$log2['money']},no_use_money=no_use_money-{$log2['money']} where user_id={$user_id}");
			
			//添加待收的金额
			unset($account_result);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log3['user_id'] 	= $user_id;
			$log3['ftype'] 		= COLLECTION;
			$log3['money'] 		= $repayment_account;
			$log3['total'] 		= $account_result['total']+$log3['money'];
			$log3['use_money'] 	= $account_result['use_money'];
			$log3['no_use_money']= $account_result['no_use_money'];
			$log3['collection'] = $account_result['collection']+$log3['money'];
			$log3['to_user'] 	= $yjb['user_id'];
			$log3['remark'] 	= "待收金额";
			$log3['add_time'] 	= $data['add_time'];
			$log3['addip'] 		= $data['addip'];
			//$this->db->insert('zjy_account_log_'.$mode, $log3);
			$this->db->query("update zjy_account set total=total+{$log3['money']},collection=collection+{$log3['money']} where user_id={$user_id}");
			
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$user_id,
				'name'=>"投资的标[<font color=red>{$yjb['title']}</font>投标成功",
				'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
				'content'=>"你所投资的标[<a href='/borrow/slobj/{$yjbId}.html' target=_blank><font color=red>{$yjb['title']}</font></a>]在".date("Y-m-d",time())."已经通过",
				'add_time'=>$data['add_time'],'addip'=>$data['addip']));
			
			//30天按一个月添加积分
			if ($data['time_limit_day']>=30){
				$vals = 16;
				$credit_value = intval($account/10000*$vals);
				//晚上双倍
				$st = strtotime(date('Y-m-d 06:00:00'));
				$et = strtotime(date('Y-m-d 18:00:00'));
				$now = time();
				if ($now<$st || $now>$et){
					$credit_value = $credit_value * 2;
				}
				
				//增加积分
				$creditNidType = $this->Credit_model->arrays('creditNidType');
				$creditTypeName = $this->Credit_model->arrays('creditTypeName');
				$credit_log = array('user_id'=>$user_id,
									'type_id'=>$creditNidType['invest_success'],
									'op'=>1,
									'credit_value'=>$credit_value,
									'remark'=>$creditTypeName[$creditNidType['invest_success']].'加'.$credit_value.'分',
									'op_user'=>$yjb['user_id'],
									'add_time'=>$data['add_time'],
									'addip'=>$data['addip']);
				$this->Credit_model->incr_credit($credit_log);	
			}
			
			
			//借款者总金额增加。
			unset($account_result);
			$account_result 	= $this->Account_model->get_account($yjb['user_id']);
			$log4['user_id'] 	= $yjb['user_id'];
			$log4['ftype'] 		= BORROW_SUCCESS;
			$log4['money'] 		= $account;
			$log4['total'] 		= $account_result['total']+$log4['money'];
			$log4['use_money'] 	= $account_result['use_money']+$log4['money'];
			$log4['no_use_money']= $account_result['no_use_money'];
			$log4['collection'] = $account_result['collection'];
			$log4['to_user'] 	= $user_id;
			$log4['remark'] 	= "通过[{$borrow_url}]借到的款";
			$log4['add_time'] 	= $data['add_time'];
			$log4['addip'] 		= $data['addip'];
			//$this->db->insert('zjy_account_log_'.$mode1, $log4);
			$this->db->query("update zjy_account set total=total+{$log4['money']},use_money=use_money+{$log4['money']} where user_id={$yjb['user_id']}");
			
			//借款手续费
			unset($account_result);
            $borrow_fee = 0;
			$borrow_fee = round(0.005*$account,2);	
			$account_result 	= $this->Account_model->get_account($yjb['user_id']);
			$log5['user_id'] 	= $yjb['user_id'];
			$log5['ftype'] 		= BORROW_FEE;
			$log5['money'] 		= $borrow_fee;
			$log5['total'] 		= $account_result['total']-$log5['money'];
			$log5['use_money'] 	= $account_result['use_money']-$log5['money'];
			$log5['no_use_money']= $account_result['no_use_money'];
			$log5['collection'] = $account_result['collection'];
			$log5['to_user'] 	= "0";
			$log5['remark'] 	= "借款[{$borrow_url}]的手续费";
			$log5['add_time'] 	= $data['add_time'];
			$log5['addip'] 		= $data['addip'];
			//$this->db->insert('zjy_account_log_'.$mode1, $log5);
			$this->db->query("update zjy_account set total=total-{$log5['money']},use_money=use_money-{$log5['money']} where user_id={$yjb['user_id']}");
			
			$this->db->trans_complete();
			if($this->db->trans_status() == 1){
				$mode = $user_id%100;
				$mode1 = $yjb['user_id']%100;
				$this->db->insert('zjy_account_log_'.$mode, $log1);
				$this->db->insert('zjy_account_log_'.$mode, $log2);
				$this->db->insert('zjy_account_log_'.$mode, $log3);
				$this->db->insert('zjy_account_log_'.$mode1, $log4);
				$this->db->insert('zjy_account_log_'.$mode1, $log5);
				//如果标满了修改标状态为已满标
				$this->db->query("update zjy_yjb_borrow set fstatus=3 where id={$yjbId} and account_yes>=account");
				
				//添加到邮件发送队列
				$yjbProtocolMailKey = "yjbProtocolMailKey";
				$mailList = $this->mycache->get_array($yjbProtocolMailKey);
				$mailList = $mailList ? $mailList : array();
				$mailList[] = array(
					'user_id' => $user_id,
					'borrow_id' => $yjbId,
					'tender_id' => $tender_id
				);
				$this->mycache->set_array($yjbProtocolMailKey,$mailList);
				
				return true;
			}else{
				return false;
			}
			
		}else{
			return false;
		}
    }
    
    function add_tender($data){
    	$this->db->insert('zjy_yjb_tender', $data);
    	$tender_id = $this->db->insert_id();
		return $tender_id;
    }
    
    function tender_list($data=array(),$is_all=false){
    	$_where = " where p1.id>0 ";
    	if (isset($data['yjb_id']) && $data['yjb_id']>0){
    		$_where .=" and p1.yjb_id='{$data['yjb_id']}'";
    	}
    	if (isset($data['user_id']) && $data['user_id']>0){
    		$_where .=" and p1.user_id='{$data['user_id']}'";
    	}
    	if (isset($data['username']) && $data['username']!=''){
    		$_where .=" and p2.username='{$data['username']}'";
    	}
    	if (isset($data['fstatus']) && $data['fstatus']>0){
    		$_where .=" and p1.fstatus='{$data['fstatus']}'";
    	}
    	if (isset($data['is_self']) && $data['is_self']>=0){
    		$_where .=" and p2.is_self={$data['is_self']}";
    	}
    	if (isset($data['time_limit_day']) && $data['time_limit_day']>0){
    		$_where .=" and p1.time_limit_day='{$data['time_limit_day']}'";
    	}
    	if (isset($data['strtime']) && $data['strtime']!=''){
    		$_where .=" and p1.add_time>=".strtotime($data['strtime']);
    	}
    	if (isset($data['endtime']) && $data['endtime']!=''){
    		$_where .=" and p1.add_time<=".strtotime($data['endtime'].' 23:59:59');
    	}
    	if (isset($data['r_strtime']) && $data['r_strtime']!=''){
    		$_where .=" and p1.repay_time>=".strtotime($data['r_strtime']);
    	}
    	if (isset($data['r_endtime']) && $data['r_endtime']!=''){
    		$_where .=" and p1.repay_time<=".strtotime($data['r_endtime'].' 23:59:59');
    	}
    	
    	
    	if ($is_all==true){
    		$sql = "select p1.*,p2.username,p2.add_time as user_reg_time,p3.title from zjy_yjb_tender as p1 
    			left join zjy_user as p2 on p1.user_id=p2.user_id 
    			left join zjy_yjb_borrow as p3 on p1.yjb_id=p3.id ".$_where." order by p1.add_time desc";
    		$query = $this->db->query($sql);
			return $query->result_array();
    	}
    	
    	$_order = "";
    	if (isset($data['order']) && $data['order']=='add_time'){
    		$_order = " order by p1.add_time desc";
    	}elseif (isset($data['order']) && $data['order']=='repay_time'){
    		$_order = " order by p1.repay_time asc";
    	}elseif (isset($data['order']) && $data['order']=='fstatus'){
    		$_order = " order by p1.fstatus asc,add_time desc";
    	}
    	
    	$_limit = "";
    	if (isset($data['per_page']) && isset($data['page_size'])){
    		$_limit = " limit {$data['per_page']},{$data['page_size']}";
    	}
    	
    	$sql = "select count(p1.id) as count from zjy_yjb_tender as p1 
    		left join zjy_user as p2 on p1.user_id=p2.user_id 
    		left join zjy_yjb_borrow as p3 on p1.yjb_id=p3.id ".$_where;
    	$query = $this->db->query($sql);
		$count = $query->row()->count;
		
		$sql = "select sum(p1.account) as total_money,sum(p1.repayment_account) as total_repay from zjy_yjb_tender as p1 
    		left join zjy_user as p2 on p1.user_id=p2.user_id 
    		left join zjy_yjb_borrow as p3 on p1.yjb_id=p3.id ".$_where;
    	$query = $this->db->query($sql);
		//$total_money = $query->row()->total_money;
		$row = $query->row_array();
		$total_money = $row['total_money'];
		$total_repay = $row['total_repay'];
		
		$sql = "select count(distinct p1.user_id) as total_people from zjy_yjb_tender as p1 
    		left join zjy_user as p2 on p1.user_id=p2.user_id 
    		left join zjy_yjb_borrow as p3 on p1.yjb_id=p3.id ".$_where;
    	$query = $this->db->query($sql);
		$total_people = $query->row()->total_people;
		
		$sql = "select p1.*,p2.username,p3.title from zjy_yjb_tender as p1 
    		left join zjy_user as p2 on p1.user_id=p2.user_id 
    		left join zjy_yjb_borrow as p3 on p1.yjb_id=p3.id ".$_where.$_order.$_limit;
		
		$query = $this->db->query($sql);
		$list = $query->result_array();
		
		return array(
			'count' => $count,
			'total_money'=>$total_money,
			'total_repay'=>$total_repay,
			'total_people' => $total_people,
			'list' => $list
		);
    	
    }
    
    /**
     * 易居宝统计
     */
    function get_total($user_id=0){
    	//fstatus=1 代收总额、本金、利息
    	$ret = array();
    	$sql = "select sum(repayment_account) as total, sum(account) as account, sum(interest) as interest  from zjy_yjb_tender where user_id={$user_id} and fstatus=1";
    	$query = $this->db->query($sql);
    	$row = $query->row_array();
    	$ret['daishou'] = array(
    		'total' => $row['total'],
    		'account'=>$row['account'],
    		'interest'=>$row['interest']
    	);
    	
    	//fstatus=3 已收总额、本金、利息
    	$sql = "select sum(repayment_account) as total, sum(account) as account, sum(interest) as interest  from zjy_yjb_tender where user_id={$user_id} and fstatus=3";
    	$query = $this->db->query($sql);
    	$row = $query->row_array();
    	$ret['yishou'] = array(
    		'total' => $row['total'],
    		'account'=>$row['account'],
    		'interest'=>$row['interest']
    	);
    	
    	//所有总额、本金、利息
    	$sql = "select sum(repayment_account) as total, sum(account) as account, sum(interest) as interest  from zjy_yjb_tender where user_id={$user_id}";
    	$query = $this->db->query($sql);
    	$row = $query->row_array();
    	$ret['all'] = array(
    		'total' => $row['total'],
    		'account'=>$row['account'],
    		'interest'=>$row['interest']
    	);
    	return $ret;
    }
    
    function yjb_total(){
    	//$sql = "SELECT yjb_id,time_limit_day,SUM(account) AS account,apr FROM zjy_yjb_tender GROUP BY yjb_id,time_limit_day;";
    	$key = "index_yjb_tongji_".date('Ymd');
    	$ret = $this->mycache->get_array($mkey);
    	if (!$ret){
    		$sql = "select sum(repayment_account) as total, sum(account) as account, sum(interest) as interest  from zjy_yjb_tender";
	    	$query = $this->db->query($sql);
	    	$ret = $query->row_array();
	    	$this->mycache->set_array($key,$ret,3600*24);
    	}
    	return $ret;
    }
    
    
    
    /**
     * 最近回款时间
     * @param $user_id
     */
    function first_repay_time($user_id){
    	$sql = "select repay_time from zjy_yjb_tender where user_id={$user_id} and fstatus=1 order by repay_time asc limit 1";
    	$query = $this->db->query($sql);
    	$row = $query->row_array();
    	if ($row){
    		return $row['repay_time'];
    	}else{
    		return 0;
    	}
    }
    
    
    
    
    /**
     * 易居宝回款
     */
    function repay(){
    	$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		//$this->load->model('Credit_model');
    	$time = time();
    	$ip = $this->input->ip_address();
		
    	$startTime = strtotime(date('Y-m-d'));
    	$endTime = $startTime+(3600*24);
    	$sql = "select p1.id,p1.user_id,p1.yjb_id,p1.repayment_account,p2.user_id as yjb_userid,p2.title   
    		from zjy_yjb_tender as p1 left join zjy_yjb_borrow as p2 on p1.yjb_id=p2.id where p1.fstatus=1 and p1.repay_time>={$startTime} and p1.repay_time<{$endTime}";
    	$query = $this->db->query($sql);
    	$list = $query->result_array();
    	$yjb_ids = array();//还款的标ID列表
    	foreach ($list as $r){
    		if (!in_array($r['yjb_id'], $yjb_ids)){
    			$yjb_ids[] = $r['yjb_id'];
    		}
    		$user_account = $this->Account_model->get_account($r['yjb_userid']);
    		if ($user_account['use_money']<$r['repayment_account']){
    			echo '还款人余额不足';
    			exit;
    		}
    		 
    		$this->db->trans_start();
    		//借款人还款
			$bmode = $r['yjb_userid']%100;
			$user_account = $this->Account_model->get_account($r['yjb_userid']);
			$log['user_id'] 		= $r['yjb_userid'];
			$log['ftype'] 			= REPAYMENT;
			$log['money'] 			= $r['repayment_account'];
			$log['total'] 			= $user_account['total']-$log['money'];
			$log['use_money'] 		= $user_account['use_money']-$log['money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection'];
			$log['to_user'] 		= "0";
			$log['remark'] 			= "对[<a href='/borrow/slobj/{$r['yjb_id']}.html' target=_blank>{$r['title']}</a>]还款";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$bmode, $log);
			$this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$r['yjb_userid']}");
			//投资人回款
    		$umode = $r['user_id']%100;
    		$user_account = $this->Account_model->get_account($r['user_id']);
    		$log['user_id'] 		= $r['user_id'];
			$log['ftype'] 			= INVEST_REPAYMENT;
			$log['money'] 			= $r['repayment_account'];
			$log['total'] 			= $user_account['total'];
			$log['use_money'] 		= $user_account['use_money']+$log['money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection']-$log['money'];
			$log['to_user'] 		= $r['yjb_userid'];
			$log['remark'] 			= "借款人对[<a href='/borrow/slobj/{$r['yjb_id']}.html' target=_blank>{$r['title']}</a>]借款的还款";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$umode, $log);
			$this->db->query("update zjy_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$r['user_id']}");
			
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$r['user_id'],
				'name'=>"借款人对[<a href='/borrow/obj/{$r['yjb_id']}.html' target=_blank>{$r['title']}</a>]借款的还款",
				'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
				'content'=>"借款人在".date("Y-m-d H:i:s")."对[<a href='/borrow/slobj/{$r['yjb_id']}.html' target=_blank>{$r['title']}</a>]借款的还款,还款金额为{$r['repayment_account']}",
				'add_time'=>$time,'addip'=>$ip));
			
			//修改投资记录状态为已还
			$this->db->query("update zjy_yjb_tender set fstatus=3,repayment_yesaccount=repayment_account,repay_yestime={$time} where id={$r['id']}");
			$this->db->trans_complete();
    	}
    	foreach ($yjb_ids as $yjb_id){//判断标是否还完
    		$sql = "select id from zjy_yjb_tender where yjb_id={$yjb_id} and fstatus=1 limit 1";
	    	$query = $this->db->query($sql);
	    	$row = $query->row_array();
	    	if (!$row){
	    		//如果没有未还的投资记录 则修改标状态为已还完
	    		$this->db->query("update zjy_yjb_borrow set fstatus=4 where id={$yjb_id}");
	    	}
    	}
    	
    }
    
    
    function yjb_auto_tender($borrow_id=0,$user_id=0){
    	//默认为48小时内有效，48小时后按照新规则重新设置。
		$valid = strtotime('2014-04-17 10:00:00')+2*3600*24;
		$now = time();
		$auto_sql = "SELECT t1.id,t1.user_id,t1.tender_type,t1.tender_account,t1.tender_account1,t1.tender_scale,
					 t1.borrow_style_status,t1.borrow_style,t1.timelimit_status,t1.timelimit_month_first,
					 t1.timelimit_month_last,t1.apr_status,t1.apr_first,t1.apr_last,t1.award_status,
					 t1.award_first,t1.award_last,t1.tender_count
					 FROM zjy_borrow_auto t1
					 left join zjy_account t2 on t1.user_id=t2.user_id
					 left join zjy_user u on t1.user_id = u.user_id
					 left join zjy_user_vip v on t1.user_id = v.user_id
					 where t1.fstatus=1  AND t2.use_money >= 50 and t1.is_del=0";
		
		if ($user_id>0){
			$auto_sql .= " and t1.user_id={$user_id}";
		}
		
		if($now>$valid){
			$auto_sql .= " and t1.valid_start_time<{$now} and t1.valid_end_time>{$now}";
		}
		
		$auto_sql .= " GROUP BY t1.user_id  ORDER BY t1.valid_start_time DESC,t1.valid_end_time DESC,v.vip_status DESC,t1.tender_count asc,t1.last_tender_time asc,u.add_time asc";
		$query = $this->db->query($auto_sql);
		$borrow_auto_list = $query->result_array();
		if ($borrow_auto_list){
			$borrow_result = self::get_by_id($borrow_id);//获取借款标的单独信息
	    	$borrow_result['apr'] = 0;
			$aprList = json_decode($borrow_result['apr_list'],true);
			foreach ($aprList as $v){
				if ($v['time_limit']==30){
					$borrow_result['apr'] = $v['apr'];//提取30天的利率
				}
			}
			if ($borrow_result['account_yes']>=$borrow_result['account']){
				return 0;
			}
			if (!$borrow_result['apr']){
				return 0;
			}
			$borrow_result['time_limit'] = 1;//30天算作1月标
			
			foreach($borrow_auto_list as $borrow_auto){
				if($borrow_result['user_id'] == $borrow_auto['user_id']){
					continue;//不能投自己的标
				}
				$tender_account  = $borrow_auto['tender_account'];
				$tender_account1 = $borrow_auto['tender_account1'];
				
				if($tender_account < $borrow_result['lowest_account']){
						continue;//不符合最低投资金额
				}
				if($borrow_auto['award_status'] == 1){
					continue;//不符合奖励要求（易居宝没有奖励，只要设置了奖励就不符合要求）
				}
				if($borrow_auto['apr_status'] == 1){
					if($borrow_auto['apr_first'] > $borrow_result['apr'] || 
						$borrow_auto['apr_last'] < $borrow_result['apr']){
						continue;//不符合利率要求
					}
				}
				if($borrow_auto['timelimit_status'] == 1){
					if($borrow_auto['timelimit_month_first'] > $borrow_result['time_limit'] || 
						$borrow_auto['timelimit_month_last'] < $borrow_result['time_limit']){
						continue;//不符合期限要求
					}
				}
				if(($borrow_result['most_account'] != 0) && ($tender_account > $borrow_result['most_account'])){
					continue;
				}
				if (($borrow_result['account']-$borrow_result['account_yes']) < $tender_account){
					$tender_account = $borrow_result['account']-$borrow_result['account_yes'];
				}
				$this->load->model('Account_model');
				$user_account = $this->Account_model->get_account($borrow_auto['user_id']);
				$expMoney = $user_account['exp_money_12']+$user_account['exp_money_24'];
				$user_account['use_money'] = $user_account['use_money'] - $expMoney;
				
				if ($user_account['use_money'] < $tender_account){
					$tender_account = $user_account['use_money'];
				}
				if($tender_account < $tender_account1){
					continue;
				}
				if ($user_account['use_money'] < $tender_account){
					continue;
				}
				if($tender_account < $borrow_result['lowest_account']){
					continue;
				}
				/*$data['id'] 			= $borrow_id;
				$data['ip'] 			= '127.0.0.1';
				$data['user_id'] 		= $borrow_auto['user_id'];
				$data['borrow_user_id'] = $borrow_result['user_id'];
				$data['money'] 			= $tender_account;
				$data['account'] 		= $tender_account;*/
				
				$data['user_id'] = $borrow_auto['user_id'];
				$data['fstatus'] = 1;
				$data['yjb_id'] = $borrow_id;
				$data['money'] = $tender_account;
				$data['account'] = $tender_account;
				$data['time_limit_day'] = 30;
				$data['apr'] = $borrow_result['apr'];
				$data['add_time'] = time();
				$data['addip'] = '127.0.0.1';
				//$res = $this->Yjb_model->invest($data);
				
				$auto_data['tender_count']=intval($borrow_auto['tender_count']+1);
				$auto_data['last_tender_time']=time();
				
				$tender_acc = floor($tender_account/$borrow_result['lowest_account']);
				if ($tender_acc<1){
					continue;
				}
				$data['account'] 	= $tender_acc*$borrow_result['lowest_account'];
				if($user_account['use_money']<$data['account']){
					continue;
				}
				
				$this->load->model('Borrow_model');
				$this->Borrow_model->update_borrow_auto($borrow_auto['id'],$auto_data);
				self::invest($data);
				//self::borrow_lz_tender($data);
			}
		}
		
		
		
    }
    
    
    function yjb_tender_cancel($id=0){
    	$id = intval($id);
    	$this->db->where('id', $id);
		$query = $this->db->get('zjy_yjb_tender');
		$tender = $query->row_array();
		$time = time();
		$ip = $this->js->get_ip();
		if (isset($tender['id']) && $tender['fstatus']==1){
			$this->load->model('Account_model');
			$this->db->trans_start();
			$mode = $tender['user_id']%100;
			//撤销投标待收扣除
			$account_result  	= $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 	= $tender['user_id'];
			$log['ftype'] 		= INVEST_CANCEL_COLL;
			$log['money'] 		= $tender['repayment_account'];
			$log['total'] 		= $account_result['total']-$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection']-$log['money'];
			$log['to_user'] 	= "1";
			$log['remark'] 		= "撤销投标待收扣除";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$mode, $log);
			$this->db->query("update zjy_account set total=total-{$log['money']},collection=collection-{$log['money']} where user_id={$tender['user_id']}");
			unset($log);
			//撤销投标本金返回
			$account_result  	= $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 	= $tender['user_id'];
			$log['ftype'] 		= INVEST_CANCEL_ACC;
			$log['money'] 		= $tender['account'];
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money']+$log['money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= "1";
			$log['remark'] 		= "撤销投标本金返回";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$mode, $log);
			$this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$tender['user_id']}");
			unset($log);
			/********* 标额度不空出，用内部账户填补 **************/
			$tuid = 329;
			$tmpTender = $tender;
			unset($tmpTender['id']);
			$tmpTender['user_id'] = $tuid;
			$tmpTender['add_time'] = $time;
			$this->db->insert('zjy_yjb_tender', $tmpTender);
			$new_tender_id = $this->db->insert_id();
			
			$this->db->where('id', $tender['yjb_id']);
			$query = $this->db->get('zjy_yjb_borrow');
			$borrow = $query->row_array();
			//投标金额冻结
			$mode = $tuid%100;
			$account_result 	= $this->Account_model->get_account($tuid);
			$log['user_id'] 	= $tuid;
			$log['ftype'] 		= TENDER;
			$log['money'] 		= $tender['account'];
			$log['total'] 		= $account_result['total'];
			$log['use_money'] 	= $account_result['use_money']-$log['money'];
			$log['no_use_money']= $account_result['no_use_money']+$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "投标冻结资金";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$mode, $log);
			$this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$tuid}");
			
			//扣除投资者的金钱。
			unset($log);
			$account_result 	= $this->Account_model->get_account($tuid);
			$log['user_id'] 	= $tuid;
			$log['ftype'] 		= INVEST;
			$log['money'] 		= $tender['account'];
			$log['total'] 		= $account_result['total']-$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money']-$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "投标成功费用扣除";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$mode, $log);
			$this->db->query("update zjy_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tuid}");
				
			//添加待收的金额
			unset($log);
			$account_result 	= $this->Account_model->get_account($tuid);
			$log['user_id'] 	= $tuid;
			$log['ftype'] 		= COLLECTION;
			$log['money'] 		= $tender['repayment_account'];
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection']+$log['money'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "待收金额";
			$log['add_time'] 	= $time;
			$log['addip'] 		= $ip;
			$this->db->insert('zjy_account_log_'.$mode, $log);
			$this->db->query("update zjy_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$tuid}");
				
			//删除投标记录表状态
			$sql = "delete from zjy_yjb_tender where id={$id}";
			$this->db->query($sql);
			
			$this->db->trans_complete();
			if($this->db->trans_status() == 1){
				return '操作成功';
			}else{
				return '操作失败';
			}
		}
    }
    
}

?>